import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 任务日志类型定义
 */
export interface TaskLog {
  id: number
  taskId: number
  taskName: string
  status: 'RUNNING' | 'SUCCESS' | 'FAILED'
  startTime: string
  endTime?: string
  duration?: number
  executer: string
  recordsProcessed?: number
  errorCount?: number
  errorMessage?: string
  createTime: string
}

/**
 * 任务日志查询参数
 */
export interface TaskLogSearchParams extends PageParams {
  taskId?: number
  taskName?: string
  status?: 'RUNNING' | 'SUCCESS' | 'FAILED'
  startTimeFrom?: string
  startTimeTo?: string
}

/**
 * 获取任务日志列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchTaskLogs = async (params: TaskLogSearchParams): Promise<PageResult<TaskLog>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<TaskLog>>>('/api/task-logs', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取任务日志失败')
    throw error
  }
}

/**
 * 获取任务日志详情
 * @param id 日志ID
 * @returns 日志详情
 */
export const getTaskLog = async (id: number): Promise<TaskLog> => {
  try {
    const { data } = await request.get<BaseResponse<TaskLog>>(`/api/task-logs/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取任务日志详情失败')
    throw error
  }
}

/**
 * 获取任务最新日志
 * @param taskId 任务ID
 * @returns 最新日志
 */
export const getLatestTaskLog = async (taskId: number): Promise<TaskLog | null> => {
  try {
    const { data } = await request.get<BaseResponse<TaskLog | null>>(`/api/tasks/${taskId}/latest-log`)
    return data.data
  } catch (error) {
    ElMessage.error('获取最新任务日志失败')
    throw error
  }
}

/**
 * 获取任务执行统计
 * @param taskId 任务ID
 * @param days 最近天数
 * @returns 执行统计
 */
export const getTaskStats = async (taskId: number, days: number = 7): Promise<{
  successCount: number
  failedCount: number
  avgDuration: number
}> => {
  try {
    const { data } = await request.get<BaseResponse<{
      successCount: number
      failedCount: number
      avgDuration: number
    }>>(`/api/tasks/${taskId}/stats`, { params: { days } })
    return data.data
  } catch (error) {
    ElMessage.error('获取任务统计失败')
    throw error
  }
}

/**
 * 清除任务日志
 * @param taskId 任务ID
 * @param days 保留最近天数
 */
export const clearTaskLogs = async (taskId: number, days: number = 30): Promise<void> => {
  try {
    await request.delete(`/api/task-logs/clear`, { params: { taskId, days } })
    ElMessage.success('任务日志清理成功')
  } catch (error) {
    ElMessage.error('清理任务日志失败')
    throw error
  }
}

// 缓存最近请求的日志数据
const taskLogCache = new Map<number, TaskLog>()

/**
 * 获取任务日志详情（带缓存）
 * @param id 日志ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 日志详情
 */
export const getTaskLogWithCache = async (id: number, forceRefresh = false): Promise<TaskLog> => {
  if (!forceRefresh && taskLogCache.has(id)) {
    return taskLogCache.get(id)!
  }

  const log = await getTaskLog(id)
  taskLogCache.set(id, log)
  return log
}
